package com.yyk.yykywd.ui.work;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yykywd.R;
import com.yyk.yykywd.adapter.MoreGridViewAdapter;
import com.yyk.yykywd.adapter.MoreGvBean;
import com.yyk.yykywd.base.BaseActivity;
import com.yyk.yykywd.config.Constant;
import com.yyk.yykywd.config.HttpUrl;
import com.yyk.yykywd.http.ApiService;
import com.yyk.yykywd.bean.WorkCreateplanInfo;
import com.yyk.yykywd.listenter.DialogSureCancelListenter;
import com.yyk.yykywd.util.DialogUtil;
import com.yyk.yykywd.util.Md5Util2;
import com.yyk.yykywd.util.OnClickFlagUtil;
import com.yyk.yykywd.util.SingleOptionsPickerUtil;
import com.yyk.yykywd.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * 创建计划
 */
public class CreatePlanActivity extends BaseActivity {
    private final int REQUEST_CODE = 1;
    @BindView(R.id.gridView)
    GridView gridView;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_time)
    EditText etTime;
    @BindView(R.id.et_end)
    EditText etEnd;
    @BindView(R.id.et_goal)
    EditText etGoal;
    @BindView(R.id.et_rests)
    EditText etRests;
    @BindView(R.id.bt_save)
    Button btSave;
    @BindView(R.id.iv_img) //照片
            ImageView ivImg;
    @BindView(R.id.tv_name)//名字
            TextView tvName;
    @BindView(R.id.tv_topname)
    TextView tvTopname;
    private long time;  //日期时间
    private int end;


    @Override
    public int getLayoutId() {
        return R.layout.activity_create_plan;
    }

    @Override
    public void initView() {
        initToolbar();
        //设置业务联系人
        Glide.with(mActivity).load(HttpUrl.BASE_PIC_URL + Hawk.get("img")).into(ivImg);
        tvName.setText(Hawk.get("name") + "");
        //设置业务类型
        tvTopname.setText(Hawk.get("topname") + "");
    }

    private void initToolbar() {
        setBackArrow();
        setTitle("创建计划");

    }

    @Override
    public void initData() {

        initAdapter();

    }

    private List<String> strings = new ArrayList<>();//查询是否有重复的值

    private List<MoreGvBean> mPicList = new ArrayList<>(); //上传的图片凭证的数据源

    MoreGridViewAdapter mGridViewAddImgAdapter;

    private void initAdapter() {
        //1.
        //这里写了一个回调，获取点击图片后的postion，并用HAWK 保存下来，调用删除接口 并去掉HAWK，实现完美删除法
        //        mPicList.add(new MoreGridViewItemInfo(null,"执业证",null));  本来想复用适配器中的布局，但是没成功
        mGridViewAddImgAdapter = new MoreGridViewAdapter(mActivity, mPicList, new MoreGridViewAdapter.DeleteItemListenter() {
            @Override
            public void onDeleteItemListenter(int postion) {
                //删除
                strings.remove(postion);
            }
        });
        gridView.setAdapter(mGridViewAddImgAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == parent.getChildCount() - 1) {
                    //如果“增加按钮形状的”图片的位置是最后一张，且添加了的图片的数量不超过3张，才能点击
                    if (mPicList.size() == Constant.MAX_SELECT_PIC_NUM2) {
                        //最多添加3张图片  暂时不做操作
                    } else {
                        //当不够二张图片的时候，可以选择照片
                        Intent intent = new Intent(mActivity, SelectImgActivity.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                } else {
                    //暂时不做操作
                }
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectImgActivity.RESULT_CODE) {
            Bundle extras = data.getExtras();
            String iv = extras.getString("iv");
            String tv = extras.getString("tv");
            String id = extras.getString("id");
            if (requestCode == REQUEST_CODE) {
                if (strings.contains(id)) {
                    ToastUtil.showShort("该业务负责人已在列表中");
                    return;
                }
                strings.add(id);
                MoreGvBean bean = new MoreGvBean(iv, tv, id);
                mPicList.add(bean);
                mGridViewAddImgAdapter.notifyDataSetChanged();
            }

        }
    }


    @OnClick({R.id.et_time, R.id.et_end, R.id.bt_save})
    public void onViewClicked(View view) {
        if (OnClickFlagUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {

            case R.id.et_time:
                //时间选择器
                TimePickerView pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        etTime.setText(getTime(date));
                        //开始时间
                        time = date.getTime() / 1000;
                    }
                }).setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                        .setTitleText("选择日期")
                        .setSubmitText("确定")//确定按钮文字
                        .setSubCalSize(15)
                        .setSubmitColor(0xff212121) //确定文字颜色
                        .setCancelText("取消 ")//取消按钮文字
                        .setSubCalSize(15)
                        .setCancelColor(0xff777777)//取消文字颜色
                        .setDividerColor(0xffD7D7D7) //分割线颜色
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(15)
                        .setLineSpacingMultiplier(2.5f) // item 间距
                        .build();
                pvTime.show(etTime);
                break;
            case R.id.et_end:
                List<String> list = new ArrayList<>();
                list.add("上午");
                list.add("下午");
//                list.add("晚上");
                SingleOptionsPickerUtil.openOptionsPicker(this, list, 1, etEnd);
                SingleOptionsPickerUtil.setOnPicker(new SingleOptionsPickerUtil.Listenter() {
                    @Override
                    public void lisenter(String value) {
                        if (value.equals("上午")) {
                            end = 1;
                        } else if (value.equals("下午")) {
                            end = 2;
                        }
//                        else {
//                            end = 3;
//                        }
                    }
                });


                break;
            case R.id.bt_save:
                String name = etName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.showShort("请填写机构名称");
                    return;
                }
                if (TextUtils.equals(time + "", "0") | TextUtils.equals(end + "", "0")) {
                    ToastUtil.showShort("请填写拜访时间");
                    return;
                }

                Logger.e(etName.toString() + "123456");

                DialogUtil.showReturnTips(mActivity, "计划创建成功", "可在您拜访机构后，进行后续业务流程", "好的", "", new DialogSureCancelListenter() {
                    @Override
                    public void onSureListenter() {
                        Map<String, String> map = new TreeMap<>();
                        map.put("uid", Hawk.get("uid") + "");
                        map.put("name", etName.getText().toString().trim());
                        map.put("time", time + "");
                        map.put("end", end + "");
                        map.put("goal", etGoal.getText().toString().trim());
                        map.put("rests", etRests.getText().toString().trim());
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < mPicList.size(); i++) {
                            String imgid = mPicList.get(i).getImgid();
                            sb.append(imgid + ",");
                        }

                        if (TextUtils.isEmpty(sb.toString())) {
                            map.put("busi_name", Hawk.get("uid") + "");
                            Logger.d("查看是为空businame" + Hawk.get("uid") + "————空");

                        } else {
                            String busi_name = sb.toString().substring(0, sb.length() - 1);
                            map.put("busi_name", Hawk.get("uid") + "," + busi_name);
                            Logger.d("查看是为空businame" + Hawk.get("uid") + "————" + busi_name);
                        }

                        map.put("sign", Md5Util2.createSign(map));
                        ApiService.getInstance().api.postWorkCreateplan(map)
                                .subscribeOn(Schedulers.io())     //调度线程
                                .observeOn(AndroidSchedulers.mainThread())
                                .unsubscribeOn(Schedulers.io())   //取消订阅
                                .subscribe(new Observer<WorkCreateplanInfo>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(WorkCreateplanInfo info) {
                                        Logger.e("创建计划" + info.toString());
                                        if (info.getCode() == 1) {
                                            finish();
                                        } else {
                                            ToastUtil.showShort(info.getMsg());
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                    }

                                    @Override
                                    public void onComplete() {
                                    }
                                });

                    }

                    @Override
                    public void onCancelListenter() {

                    }
                }, true);

                break;
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }


}